﻿namespace CatClient.Message.Spi.Heartbeat.Extend
{
    using CatClient.Util;
    using System;
    using System.Collections.Generic;
    using System.Diagnostics;

    public class ProcessIO : HeartbeatExtention, IDisposable, IProcessPerformance
    {
        private readonly Stopwatch _stopwatch = new Stopwatch();
        private readonly Dictionary<string, double> _dict;
        private readonly PerformanceCounter _readBytesSec;
        private readonly PerformanceCounter _writeByteSec;
        private readonly PerformanceCounter _otherBytesSec;
        private readonly PerformanceCounter _totalBytesSec;

        public ProcessIO()
        {
            this._stopwatch.Start();
            this._dict = new Dictionary<string, double>();
            this._readBytesSec = this.CurrentProcessCounter("IO Read Bytes/sec");
            this._writeByteSec = this.CurrentProcessCounter("IO Write Bytes/sec");
            this._otherBytesSec = this.CurrentProcessCounter("IO Other Bytes/sec");
            this._totalBytesSec = this.CurrentProcessCounter("IO Data Bytes/sec");
            this._stopwatch.Stop();
            LogInfoWriter.GetInstance("Cat", 0, LogInfoWriter.LogLayout.Default).Info($"Heartbeat {"ProcessIO"} init finish. {this._stopwatch.ElapsedMilliseconds}ms");
        }

        public void Dispose()
        {
            if (this._readBytesSec != null)
            {
                this._readBytesSec.Dispose();
            }
            if (this._writeByteSec != null)
            {
                this._writeByteSec.Dispose();
            }
            if (this._otherBytesSec != null)
            {
                this._otherBytesSec.Dispose();
            }
            if (this._totalBytesSec != null)
            {
                this._totalBytesSec.Dispose();
            }
            GC.SuppressFinalize(this);
        }

        public override void Refresh()
        {
            this._stopwatch.Restart();
            this._dict["Read"] = this._readBytesSec.NextValue();
            this._dict["Write"] = this._writeByteSec.NextValue();
            this._dict["Other"] = this._otherBytesSec.NextValue();
            this._dict["Total"] = this._totalBytesSec.NextValue();
            this._stopwatch.Stop();
            LogInfoWriter.GetInstance("Cat", 0, LogInfoWriter.LogLayout.Default).Info($"Heartbeat {"CpuInfo"} refresh finish. {this._stopwatch.ElapsedMilliseconds}ms");
        }

        public override string Id =>
            "ProcessIO";

        public override Dictionary<string, double> Dict =>
            this._dict;
    }
}

